package com.zkzx.util.data;

import lombok.extern.slf4j.Slf4j;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author young Email:yanghui@zkraising.com
 * @description
 * @company 北京中科智兴物联科技有限公司 @版权所有
 * @since 2021年05月07日 10时26分
 */
@Slf4j
public class RandomStringGenerator {

    RandomStringGenerator(){}

    /**
     * 获取一定长度的随机字符串
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public static String getRandomStringByLength(int length) {
        try {
            String base = "abcdefghijklmnopqrstuvwxyz0123456789";
            SecureRandom random = SecureRandom.getInstanceStrong();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
           log.error("生成随机字符串失败：",e);
        }
        return null;
    }

    /**
     * 获取一定长度的随机数值串
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
    public static String getRandomIntgerByLength(int length) {
        try {
            String base = "0123456789";
            SecureRandom random = SecureRandom.getInstanceStrong();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("生成随机数值失败：",e);
        }
        return null;
    }


}
